package com.opener.web.auth.utils;

import com.opener.common.encrypt.EncryptUtils;
import com.opener.common.utils.Utils;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.opener.web.auth.constant.HttpHeaderField.AUTH_REQUEST_SIGNATURE;

/**
 *
 * @author baboy
 * @date 12/10/2017
 */
public class HttpRequestAuthUtils {
    private static int tokenExpiresInSeconds = 10*60;

    public static boolean checkRequest(HttpServletRequest request, int expiresInSeconds, String checkContent){
        String token = request.getHeader(AUTH_REQUEST_SIGNATURE);
        //如果没有传入token则不处理
        if(token == null){
            return false;
        }
        //解密token，解密不出来则不处理
        Map map = EncryptUtils.parse(token);
        if (map == null){
            return false;
        }
        //解密版本不一致也不处理
        String ver = (String)map.get(EncryptUtils.MAP_KEY_VER);
        if (!EncryptUtils.VER_AC.equalsIgnoreCase(ver)){
            return false;
        }
        //1、判断是否在有效期内
        int t = Utils.parseInt(map.get(EncryptUtils.MAP_KEY_TIME));
        long timeDiff = Math.abs(System.currentTimeMillis() - t*1000L);
        if (timeDiff > expiresInSeconds*1000){
            return false;
        }
        if (checkContent != null){
            String salt = (String)map.get(EncryptUtils.MAP_KEY_SALT);
            String s = DigestUtils.sha1Hex(checkContent);
            String content = (String)map.get(EncryptUtils.MAP_KEY_CONTENT);
            if (!s.equalsIgnoreCase(content)){
                return false;
            }
        }
        return true;
    }
    public static boolean checkRequest(HttpServletRequest request, int expiresInSeconds) {
        return checkRequest(request, tokenExpiresInSeconds,null);
    }
        public static boolean checkRequest(HttpServletRequest request){
        return checkRequest(request, tokenExpiresInSeconds,null);
    }
}
